// filnavn : dispport.c			
// displayrutiner til LCD displaymodul
// tilsluttet til Port0 DB0-DB7
// E, RS og R/W som angivet i defines 
// revideret : SH 18/12-02		


#include <reg66x.h>
#include <string.h>

sbit E = P1^4;
sbit RS = P3^6;
sbit RW = P3^7;

void cursor(unsigned char, unsigned char);
void cld(void);

void D_CONTROL(unsigned char x)
{
RS = 0; RW = 0;
P0 = x;
E = 1;
E = 0;
P0 = 0xFF;
RS = 1; RW = 1;
}

unsigned char D_STATUS(void)
{
unsigned char x;
P0 = 0xFF;
RS = 0; RW = 1;
E = 1;
x = P0;
E = 0;
RS = 1;
return(x);

}

void D_WRITE(unsigned char x)
{
RS = 1; RW = 0;
P0 = x;
E = 1;
E = 0;
P0 = 0xFF;
RW = 1;
}

void init_display(void)
	{
	int x;
        E = 0;
	for(x=0; x<4800; x++);		/* 30mS delay @11 MHz*/
	D_CONTROL(0x38);		/* reset af HD 44780 */
	for (x=0; x<2400; x++);		/* 15 mS delay @11MHz*/
	D_CONTROL(0x38);
	for (x=0; x<60; x++);		/* 400uS delay @11MHz*/
	D_CONTROL(0x38);
	for(x=0; x<60; x++);		/* 400uS delay @11HMz*/
	D_CONTROL(0x38);
	while(D_STATUS() & 0x80);	/* vent til busy-flag = 0 */
	D_CONTROL(0x06);		/* Entry mode */
	while(D_STATUS() & 0x80);		
	D_CONTROL(0x0C);		/* Display ON/OFF control */
	while(D_STATUS() & 0x80);
	D_CONTROL(0x01);		/* Clear display */
	while(D_STATUS() & 0x80);
      	cursor(1,1);
	cld();
	}


void cursor(char rk, char pos)
	{
	unsigned char x;

	if (rk == 2)
		x = 192;
	else
		x = 128;
	if (pos < 25)
		x = x+pos-1;
	D_CONTROL(x);
	while(D_STATUS() & 0x80);		/* vent til busy-flag = 0 */
	}



void cld(void)
	{
	D_CONTROL(1);
	while(D_STATUS() & 0x80);    	/* vent til busy-flag = 0 */
	}


char putchar(char c)
	{
	if(c != '\n')
		{
		D_WRITE(c);
		while(D_STATUS() & 0x80);		/* vent til busy-flag = 0 */
		}
	return c;
	}
